// Decompiled by DJ v3.9.9.91 Copyright 2005 Atanas Neshkov  Date: 2008-7-11 22:41:51
// Home Page : http://members.fortunecity.com/neshkov/dj.html  - Check often for new version!
// Decompiler options: packimports(3) 
// Source File Name:   SecurityFilter.java

package com.creawor.hz_market.filter;

import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import com.creawor.hz_market.t_role.t_role;
import com.creawor.hz_market.t_user.t_user;
import com.creawor.hz_market.util.LoginUtils;
import com.creawor.hz_market.util.UserNotLoginException;
import com.creawor.km.util.CatcheUtil;

public class SecurityFilterbak extends OncePerRequestFilter
{
	protected final transient Log log = LogFactory.getLog(getClass());

    public SecurityFilterbak()
    {
    }

    public void destroy()
    {
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException
    {
        if(isExelude(request.getRequestURI()))
        {
            chain.doFilter(request, response);
            return;
        }
        if(isInclude(request.getRequestURI()))
        {
            checkPath(request, response, chain);
            
            
        }
        else
            chain.doFilter(request, response);
    }

    private boolean checkRole(HttpServletRequest request,
			HttpServletResponse response) 
    throws IOException, ServletException
    {
		
    	try
        {
            com.creawor.hz_market.bean.UserDetails user = LoginUtils.getLoginUser(request);
            //log.info("user="+user);
            if(user == null)
            {
            	response.sendRedirect((new StringBuilder(String.valueOf(request.getContextPath()))).append("/login.jsp").toString());
                return false;
            }
            t_user tuser=user.getUser();
            if(tuser.getRoles()==null)
            	return true;
            
            try {
            	String uri =request.getRequestURI();
            	uri = uri.substring(uri.lastIndexOf("/")+1);
//				t_function_QueryMap  query = new t_function_QueryMap();
				
				
            	for (Iterator iterator = tuser.getRoles().iterator(); iterator.hasNext();) 
            	{
					t_role role = (t_role) iterator.next();
					Set set =role.getFunctions();
					if(set==null)
						continue;
					String sql = "select b.url from t_role_function a, t_function b where a.functionid=b.id and a.roleid="+role.getId();
//					System.out.println("sql="+sql);
					List ls = null;
					ls=(List)CatcheUtil.getInstance().getObject(sql);
					if(null==ls || ls.size()<1){
						ls = com.creawor.hz_market.util.ComQuery.find(sql);
						CatcheUtil.getInstance().cacheObj(sql, ls);
					}
//					for (Iterator iterator2 = set.iterator(); iterator2.hasNext();) {
//						t_function function = (t_function) iterator2.next();
//						String url =function.getUrl();
////						System.out.println("url="+url+" and uri="+uri);
//						if(uri.equals(url))
//						{
//							return true;
//						}
//					}
					for (Iterator iterator2 = ls.iterator(); iterator2.hasNext();) {
						Map function = (Map) iterator2.next();
						String url =(String)function.get("url");
//						System.out.println("url="+url+" and uri="+uri);
						if(uri.equals(url))
						{
							return true;
						}
					}	
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
            
        }
        catch(UserNotLoginException e)
        {
            e.printStackTrace();
//            request.getRequestDispatcher("/login.jsp").forward(request, response);
            
        }
        return false;
	}

	private void checkPath(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException
    {
        try
        {
            com.creawor.hz_market.bean.UserDetails user = LoginUtils.getLoginUser(request);
            //log.info("user="+user);
            if(user == null)
            {
//            	request.getRequestDispatcher("/login.jsp").forward(request, response);
                response.sendRedirect((new StringBuilder(String.valueOf(request.getContextPath()))).append("/login.jsp").toString());
                return;
            }
            if(!checkRole(request, response))
            {
//            	log.info("error role,redirect to ....roleErrors.jsp");
            	response.sendRedirect((new StringBuilder(String.valueOf(request.getContextPath()))).append("/roleErrors.jsp").toString());
                return;
            }
            chain.doFilter(request, response);
        }
        catch(UserNotLoginException e)
        {
            e.printStackTrace();
//            request.getRequestDispatcher("/login.jsp").forward(request, response);
            response.sendRedirect((new StringBuilder(String.valueOf(request.getContextPath()))).append("/login.jsp").toString());
        }
    }

    private boolean isExelude(String requestURI)
    {
        for(int i = 0; i < excludeList.size(); i++)
        {
            String antPath = (String)excludeList.get(i);
            AntPathMatcher matcher = new AntPathMatcher();
            if(matcher.match(antPath, requestURI))
                return true;
        }

        return false;
    }

    private boolean isInclude(String requestURI)
    {
        for(int i = 0; i < includeList.size(); i++)
        {
            String antPath = (String)includeList.get(i);
            AntPathMatcher matcher = new AntPathMatcher();
            if(matcher.match(antPath, requestURI))
                return true;
        }

        return false;
    }

    protected void initFilterBean()
        throws ServletException
    {
        super.initFilterBean();
        try
        {
            init0(getFilterConfig());
        }
        catch(IOException e)
        {
            throw new IllegalStateException("security filter config error");
        }
    }

    private void init0(FilterConfig config)
        throws IOException
    {
        String excludes = config.getInitParameter("excludes");
        Assert.hasText(excludes, "excludes param must be not empty");
        excludeList = IOUtils.readLines(new StringReader(excludes));
        trimAll(excludeList);
        String includes = config.getInitParameter("includes");
        Assert.hasText(includes, "includes param must be not empty");
        includeList = IOUtils.readLines(new StringReader(includes));
        trimAll(includeList);
    }

    private void trimAll(List strings)
    {
        for(int i = 0; i < strings.size(); i++)
            strings.set(i, ((String)strings.get(i)).trim());

    }

    protected String getAlreadyFilteredAttributeName()
    {
        return getClass().getName();
    }

    public static void main(String args[])
    {
        AntPathMatcher matcher = new AntPathMatcher();
        System.out.println(matcher.match("/abc/*.txt", "/abc/diy.txt"));
    }

    List excludeList;
    List includeList;
}